﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GoodStuff.Data;

namespace GoodStuff.Heartbeat.Core
{
    public class SensorService : ISensorService
    {
        public IEnumerable<Data.SensorReading> GetSensorReadings(int sensorID, int channelID, DateTime from, DateTime end, TimeSpan interval)
        {
            using (var db = new GoodStuff.Data.DataContextBuilder().EnableObjectTracking().Build())
            {
                var sensorvalues = db.Where<Core.Data.SensorReading>(p => p.SensorID == sensorID && p.Channel == channelID && p.Timestamp >= from && p.Timestamp <= end);

                //group the sensor readings by the interval, currently, only MINUTE interval is supported.
                var output = sensorvalues.ToList()
                    .GroupBy(p => p.Timestamp.RoundTo(DateTimeRoundOption.Minute, interval.Minutes))
                    .Select(p => new Data.SensorReading() { Timestamp = p.Key, Value = p.Average(g => g.Value) });

                return output;
            }
        }


        public IEnumerable<SensorChannelInfo> GetSensorInfo()
        {
            int sensorId = 1;
            foreach (var component in Settings.components)
            {
                foreach (var sensor in component.Sensors)
                {
                    //sensor.Values.First().
                    int channelId = 0;
                    foreach (var channel in sensor.Values)
                    {
                        MonitorState state = MonitorState.Healthy;
                        //quick and dirty monitor implementation.
                        if (channel.Value >= channel.DefaultHigh || channel.Value <= channel.DefaultLow)
                        {
                            state = MonitorState.Warning;
                        }

                        yield return new SensorChannelInfo() { Name = component.Name + "/" + channel.Description, SensorID = sensorId, ChannelID = channelId, State = state };
                        channelId++;
                    }
                    sensorId++;
                }
            }
        }
    }
}
